import { Injectable } from '@angular/core';
import { HttpParams } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { environment } from '../../../environments/environment';

/**
 * Base Http service
 * 
 * Author: Sorin Spiru
 * Date: 13.01.2018
 */
@Injectable()
export class BaseHttpService {
    public readonly serverUrl: string = environment.serviceUrl;
    
    /**
      * Prepare object as http parameter
     * @param object Object to pe converted
     * @param previous Previous parameters. If defined, object fields are appended
     * @param exclude Because of the HttpClient issue with encoding special characters as param values, we explicitly set the params into url. So they should not be added as HttpParams
     */
    public urlEncodeObject(object: any, previous?: HttpParams, exclude: string = undefined): HttpParams {
        var ret = previous ? previous : new HttpParams();
        for (var field in object) {
            if (object[field] instanceof Array) {
                for (var i = 0; i < object[field].length; i++) {
                    if(exclude === undefined || field != exclude)
                        ret = ret.append(field, object[field][i]);
                }
            }
            else if(exclude === undefined || field != exclude){
                ret = ret.set(field, object[field]);
            }
        }

        return ret;
    }

    public paramEncode(object: any, field: string): string {
        if(object && object.hasOwnProperty(field))
            return encodeURIComponent(object[field]);
        else 
            return '';
    }
}